package com.rectcircle.scalatrateset.auth.strategies

import javax.servlet.http.{HttpServletRequest, HttpServletResponse}

import com.rectcircle.scalatrateset.model.User

import org.scalatra.ScalatraBase

import org.scalatra.auth.ScentryStrategy

/**
  * Created by sunben960729 on 2016/12/30.
  */
class UserLoginStrategy(protected val app: ScalatraBase)(implicit request: HttpServletRequest, response: HttpServletResponse) extends ScentryStrategy[User] {
	
	//定义策略名
	override def name: String = "UserLogin"
	
	//获取请求参数
	private def login = app.params.getOrElse("username", "")
	private def password = app.params.getOrElse("password", "")
	
	
	/***
	  * 确定当前策略是否应为当前请求运行，比如没有填写用户名、密码
	  */
	override def isValid(implicit request: HttpServletRequest) = {
		login != "" && password != ""
	}
	
	/**
	  *  必须实现的方法
	  *  在真实的项目中，这里应该查询数据源（如数据库或缓存），判断密码等是否匹配
	  *  为了方便用户，我们只验证用户名密码，如果成功返回这个用户的实体
	  */
	override def authenticate()(implicit request: HttpServletRequest, response: HttpServletResponse): Option[User] = {
		if(login == "foo" && password == "foo") {
			Some(new User("foo","foo"))
		} else {
			None
		}
	}
	
	/**
	  * 如果用户目前没有验证，应该发生什么？
	  * 也就是说，用户未登陆，一般跳转到登陆页面
	  */
	override def unauthenticated()(implicit request: HttpServletRequest, response: HttpServletResponse) {
		app.redirect("/login")
	}
}
